import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/data/content_repository.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/page/upload/create_page.dart';

class ChallengePage extends StatefulWidget {
  const ChallengePage({super.key});

  @override
  State<ChallengePage> createState() => _ChallengePageState();
}

class _ChallengePageState extends State<ChallengePage> {
  late int currentActiveIndex;
  List<ContentSubmission> userChallengeShares = [];
  bool isLoadingShares = false;

  @override
  void initState() {
    super.initState();
    currentActiveIndex = DateTime.now().weekday - 1;
    _loadUserChallengeShares();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.lightBlue,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _renderTopNavSection(),

              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 16.h),

                      Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20.r),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 16.h,
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            MyText(
                              text: 'Challenge Task',
                              type: TextType.miSans,
                              fontSize: 20.sp,
                              fontWeight: FontWeight.w600,
                              color: AppColors.black,
                            ),
                            MyText(
                              text: 'Take a photo and check in',
                              type: TextType.miSans,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w300,
                              color: AppColors.black,
                            ),

                            Container(
                              margin: EdgeInsets.only(top: 16.h, bottom: 16.h),
                              width: double.infinity,
                              decoration: BoxDecoration(
                                color: AppColors.blue,
                                borderRadius: BorderRadius.circular(20.r),
                              ),
                              padding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 16.h,
                              ),
                              child: Row(
                                children: [
                                  Container(
                                    width: 4.w,
                                    height: 20.h,
                                    decoration: BoxDecoration(
                                      color: AppColors.white,
                                    ),
                                  ),
                                  SizedBox(width: 12.w),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth: 254.w,
                                    ),
                                    child: MyText(
                                      text:
                                          'Participate in different challenge tasks every day and develop good health habits',
                                      type: TextType.miSans,
                                      fontSize: 12.sp,
                                      fontWeight: FontWeight.w300,
                                      color: AppColors.black,
                                      maxLines: 2,
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            _generateTaskMatrix(),
                          ],
                        ),
                      ),

                      SizedBox(height: 16.h),

                      AspectRatio(
                        aspectRatio: 343 / 205,
                        child: Container(
                          width: double.infinity,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                'assets/images/challenge-card.png',
                              ),
                              fit: BoxFit.cover,
                            ),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Container(
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  color: Color(0xFFDCF9FD),
                                  borderRadius: BorderRadius.circular(16.r),
                                  border: Border.all(color: AppColors.border),
                                ),
                                padding: EdgeInsets.all(16.w),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    MyText(
                                      text: 'Health Challenge',
                                      type: TextType.rubik,
                                      fontSize: 24.sp,
                                      fontWeight: FontWeight.w900,
                                      color: AppColors.black,
                                    ),

                                    SizedBox(height: 16.h),
                                    _createWeeklySelector(),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),

                      SizedBox(height: 16.h),

                      Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.white.withValues(alpha: 0.8),
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(color: AppColors.blue),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 16.h,
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            MyText(
                              text: 'Challenge Record',
                              type: TextType.rubik,
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w900,
                              color: AppColors.black,
                            ),

                            SizedBox(height: 16.h),

                            _assembleProgressDisplay(),
                          ],
                        ),
                      ),

                      SizedBox(height: 66.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _assembleProgressDisplay() {
    if (isLoadingShares) {
      return Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: Center(
          child: CircularProgressIndicator(
            color: AppColors.blue,
            strokeWidth: 2.w,
          ),
        ),
      );
    }

    final selectedDateShares = _getSelectedDateShares();

    if (selectedDateShares.isEmpty) {
      return _buildEmptyState();
    }

    return Column(
      children:
          selectedDateShares
              .map((share) => _buildChallengeShareItem(share))
              .toList(),
    );
  }

  Widget _buildEmptyState() {
    final currentUser = context.read<AuthCubit>().state.currentUser;
    final selectedDate = _getSelectedDate();
    final isToday = _isSelectedDateToday();

    if (currentUser == null) {
      return GestureDetector(
        onTap: () {
          context.push('/auth');
        },
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: AppColors.lightBlue.withValues(alpha: 0.3),
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(color: AppColors.blue.withValues(alpha: 0.3)),
          ),
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h),
          child: Column(
            children: [
              Icon(Icons.login, size: 32.w, color: AppColors.textGrey),
              SizedBox(height: 12.h),
              MyText(
                text: 'Login to view your challenge records',
                type: TextType.miSans,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: AppColors.textGrey,
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 8.h),
              MyText(
                text: 'Tap to login',
                type: TextType.miSans,
                fontSize: 12.sp,
                fontWeight: FontWeight.w400,
                color: AppColors.blue,
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    } else {
      return Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: AppColors.lightBlue.withValues(alpha: 0.3),
          borderRadius: BorderRadius.circular(10.r),
          border: Border.all(color: AppColors.blue.withValues(alpha: 0.3)),
        ),
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h),
        child: Column(
          children: [
            Icon(Icons.calendar_today, size: 32.w, color: AppColors.textGrey),
            SizedBox(height: 12.h),
            MyText(
              text:
                  isToday
                      ? 'No challenge completed today\nStart your first challenge!'
                      : 'No challenge completed on ${_formatDate(selectedDate)}',
              type: TextType.miSans,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: AppColors.textGrey,
              textAlign: TextAlign.center,
              maxLines: 2,
            ),
          ],
        ),
      );
    }
  }

  Widget _buildChallengeShareItem(ContentSubmission share) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment(0.00, 0.50),
          end: Alignment(1.00, 0.50),
          colors: [const Color(0xFFA7EDC8), const Color(0xFFB0F2FF)],
        ),
        borderRadius: BorderRadius.circular(10.r),
      ),
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 15.h),
      margin: EdgeInsets.only(bottom: 8.h),
      child: Row(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 4.w,
                    height: 10.h,
                    decoration: BoxDecoration(color: AppColors.white),
                  ),
                  SizedBox(width: 8.w),
                  // 时间
                  MyText(
                    text: _formatDateTime(share.publishedAt),
                    type: TextType.miSans,
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w500,
                    color: AppColors.black,
                  ),
                ],
              ),
              SizedBox(height: 16.h),
              Container(
                margin: EdgeInsets.only(left: 12.w),
                constraints: BoxConstraints(maxWidth: 200.w),
                child: MyText(
                  text: _getChallengeTitle(share),
                  type: TextType.miSans,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColors.black,
                  maxLines: 2,
                ),
              ),
            ],
          ),

          const Spacer(),
          Image.asset(
            'assets/images/complete.png',
            width: 40.w,
            height: 40.w,
            fit: BoxFit.contain,
          ),
          SizedBox(width: 16.w),
        ],
      ),
    );
  }

  Widget _generateTaskMatrix() {
    return GridView.count(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      crossAxisCount: 2,
      crossAxisSpacing: 12.w,
      mainAxisSpacing: 12.h,
      childAspectRatio: 146 / 188,
      children: [
        _constructTaskItem(
          title: 'Brush Teeth\nEvery Day',
          imagePath: 'assets/images/challenge_brush.png',
          backgroundColor: Colors.transparent,
        ),
        _constructTaskItem(
          title: 'Daily Dental\nFloss',
          imagePath: 'assets/images/challenge_floss.png',
          backgroundColor: Colors.transparent,
        ),
        _constructTaskItem(
          title: 'Food\nCheck-In',
          imagePath: 'assets/images/challenge_food.png',
          backgroundColor: Colors.transparent,
        ),
        _constructTaskItem(
          title: 'Stay Tuned',
          imagePath: '',
          backgroundColor: Color(0xFFE8E8E8),
          isComingSoon: true,
        ),
      ],
    );
  }

  Widget _constructTaskItem({
    required String title,
    required String imagePath,
    required Color backgroundColor,
    bool isComingSoon = false,
  }) {
    return GestureDetector(
      onTap: isComingSoon ? null : () => _handleTaskSelection(title),
      child: Container(
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Stack(
          children: [
            // 背景图片或占位符
            if (!isComingSoon && imagePath.isNotEmpty)
              Positioned.fill(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(16.r),
                  child: Image.asset(imagePath, fit: BoxFit.cover),
                ),
              ),

            // 内容
            Positioned.fill(
              child:
                  isComingSoon
                      ? Center(
                        child: MyText(
                          text: title,
                          type: TextType.miSans,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: AppColors.textGrey,
                          maxLines: 2,
                          textAlign: TextAlign.center,
                        ),
                      )
                      : Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Spacer(),
                          Container(
                            decoration: BoxDecoration(
                              color: AppColors.white,
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            padding: EdgeInsets.only(top: 2.h),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 8.h,
                              ),
                              decoration: BoxDecoration(
                                color: AppColors.blue,
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                    child: MyText(
                                      text: title,
                                      type: TextType.miSans,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w600,
                                      color: AppColors.black,
                                      maxLines: 2,
                                    ),
                                  ),
                                  Container(
                                    width: 28.w,
                                    height: 28.h,
                                    decoration: BoxDecoration(
                                      color: AppColors.white,
                                      borderRadius: BorderRadius.circular(50.r),
                                    ),
                                    child: Center(
                                      child: MyText(
                                        text: 'Go',
                                        type: TextType.miSans,
                                        fontSize: 12.sp,
                                        fontWeight: FontWeight.w600,
                                        color: AppColors.black,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _createWeeklySelector() {
    final DateTime now = DateTime.now();

    final int daysFromMonday = now.weekday - 1;
    final DateTime monday = now.subtract(Duration(days: daysFromMonday));

    final List<Map<String, dynamic>> dateCollection = List.generate(7, (index) {
      final DateTime currentDay = monday.add(Duration(days: index));
      final List<String> weekdayNames = [
        'Mo',
        'Tu',
        'We',
        'Th',
        'Fr',
        'Sa',
        'Su',
      ];

      return {
        'day': currentDay.day.toString(),
        'weekday': weekdayNames[index],
        'date': currentDay,
      };
    });

    final int todayIndex = now.weekday - 1;

    return SizedBox(
      height: 66.h,
      child: Row(
        children:
            dateCollection.asMap().entries.map((entry) {
              final int index = entry.key;
              final Map<String, dynamic> itemInfo = entry.value;
              final bool isActive = index == currentActiveIndex;
              final bool isCurrent = index == todayIndex;

              return Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      currentActiveIndex = index;
                    });
                    _loadUserChallengeShares();
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                      right: index == dateCollection.length - 1 ? 0 : 4.w,
                    ),
                    decoration: BoxDecoration(
                      color: isActive ? null : Color(0xFFF6FFEE),
                      gradient:
                          isActive
                              ? LinearGradient(
                                begin: Alignment(1.01, 0.00),
                                end: Alignment(0.01, 1.00),
                                colors: [
                                  const Color(0xFF95F2FD),
                                  const Color(0xFFB0FED3),
                                ],
                              )
                              : null,
                      borderRadius: BorderRadius.circular(10.r),
                      border: Border.all(
                        color:
                            isActive
                                ? AppColors.tabBlue
                                : (isCurrent
                                    ? AppColors.border
                                    : AppColors.blue),
                        width: isCurrent && !isActive ? 2.w : 1.w,
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        MyText(
                          text: itemInfo['day'],
                          type: TextType.miSans,
                          fontSize: 18.sp,
                          fontWeight: FontWeight.w600,
                          color: isActive ? AppColors.black : AppColors.black,
                        ),
                        SizedBox(height: 4.h),
                        MyText(
                          text: itemInfo['weekday'],
                          type: TextType.miSans,
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          color:
                              isActive ? AppColors.black : AppColors.textGrey,
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }).toList(),
      ),
    );
  }

  void _handleTaskSelection(String title) {
    String challengeTaskId;

    switch (title) {
      case 'Brush Teeth\nEvery Day':
        challengeTaskId = 'brush_teeth';
        break;
      case 'Daily Dental\nFloss':
        challengeTaskId = 'dental_floss';
        break;
      case 'Food\nCheck-In':
        challengeTaskId = 'daily_food';
        break;
      default:
        return;
    }

    context.push(
      '/create',
      extra: {
        'uploadType': ContentUploadType.challengeShare,
        'challengeTask': challengeTaskId,
      },
    );
  }

  Widget _renderTopNavSection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
      child: Row(
        children: [
          BlackButton(
            icon: IconFontIcons.iconArrowLeft,
            onTap: () => context.pop(),
          ),
          Expanded(
            child: Center(
              child: MyText(
                text: 'Challenge',
                type: TextType.rubik,
                fontSize: 28.sp,
                color: AppColors.black,
                fontWeight: FontWeight.w900,
              ),
            ),
          ),
          SizedBox(width: 26.w),
        ],
      ),
    );
  }

  Future<void> _loadUserChallengeShares() async {
    final currentUser = context.read<AuthCubit>().state.currentUser;
    if (currentUser == null) {
      setState(() {
        userChallengeShares = [];
        isLoadingShares = false;
      });
      return;
    }

    setState(() {
      isLoadingShares = true;
    });

    try {
      final contentRepository = ContentRepository();
      final allSubmissions = await contentRepository.getSubmissionsByAuthor(
        currentUser.id,
      );

      final challengeShares =
          allSubmissions
              .where(
                (submission) =>
                    submission.category == SubmissionCategory.challengeShare,
              )
              .toList();

      setState(() {
        userChallengeShares = challengeShares;
        isLoadingShares = false;
      });
    } catch (e) {
      setState(() {
        userChallengeShares = [];
        isLoadingShares = false;
      });
    }
  }

  List<ContentSubmission> _getSelectedDateShares() {
    final selectedDate = _getSelectedDate();

    return userChallengeShares.where((share) {
      final shareDate = share.publishedAt;
      return shareDate.year == selectedDate.year &&
          shareDate.month == selectedDate.month &&
          shareDate.day == selectedDate.day;
    }).toList();
  }

  DateTime _getSelectedDate() {
    final DateTime now = DateTime.now();
    final int daysFromMonday = now.weekday - 1;
    final DateTime monday = now.subtract(Duration(days: daysFromMonday));
    return monday.add(Duration(days: currentActiveIndex));
  }

  bool _isSelectedDateToday() {
    final selectedDate = _getSelectedDate();
    final today = DateTime.now();
    return selectedDate.year == today.year &&
        selectedDate.month == today.month &&
        selectedDate.day == today.day;
  }

  String _formatDate(DateTime date) {
    return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
  }

  String _formatDateTime(DateTime dateTime) {
    return '${_formatDate(dateTime)} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  String _getChallengeTitle(ContentSubmission share) {
    if (share.associatedTask != null) {
      return share.associatedTask!.taskTitle;
    }

    final description = share.textDescription.toLowerCase();
    if (description.contains('brush') ||
        description.contains('tooth') ||
        description.contains('teeth')) {
      return 'Brush Teeth Every Day';
    } else if (description.contains('floss')) {
      return 'Daily Dental Floss';
    } else if (description.contains('food') || description.contains('eat')) {
      return 'Daily Food Check-In';
    } else if (description.contains('challenge')) {
      return 'Health Challenge';
    }

    return 'Daily Health Challenge';
  }
}
